
var siteim_ws_protocol = 'wss'; // ws 或 wss

var siteim_server = '127.0.0.13';
var siteim_port = 93253;

var siteim_heartbeatTimeout = 90 * 1000; // 心跳超时时间，单位：毫秒
var siteim_reconnInterval = 10 * 1000;   // 重连间隔时间，单位：毫秒

var siteim_binaryType = 'arraybuffer'; // 'blob' or 'arraybuffer';//arraybuffer是字节
var siteim_handler = new SiteImHandler();

var siteim_tiows;

function siteim_initWs() {

	var param = null; //'t-io=11&userid=adfadsf';
	siteim_tiows = new tio.ws(//new  了一个SiteImHandler 于第三个参数
		function(reconn) {
			ajax.get('/im/imserver', {
				data: {
					groupid: encodeURIComponent(location.pathname)
				},
				async: false,
				timeout: 1000,
				success: function(resp) {
					var data = resp.data;
					siteim_server = data.ip;
					siteim_port = data.port;
					log('imserver---------------->', data);
				}
			});
			var queryString = sessionName + '=' + encodeURIComponent(sessionValue);
			if (tesft_tio_fdfdse) {
				queryString = queryString + '&' + tesoegEgac + '=' + encodeURIComponent(tesft_tio_fdfdse);
			}
			var url = siteim_ws_protocol + '://' + siteim_server + ':' + siteim_port + '?' + queryString;

			if (reconn) {
				url += '&tiows_reconnect=true';
			}
			console.log("url-------------->",url);
			return url;
		},
		param,
		siteim_handler,
		siteim_heartbeatTimeout,
		siteim_reconnInterval,
		siteim_binaryType
	);
	log("实例对象siteim_tiows "+JSON.stringify(siteim_tiows)+"  "+siteim_tiows.hasOwnProperty("send") );
	siteim_tiows.connect();
}

var siteim = {
	groupid: 19821015,
	/**
   * 
   * @param {*} command  SiteImCommand
   * @param {*} bodyObj  {}对象
	 * Basic Usage

     var uint8array = new TextEncoder().encode(string);
     var string = new TextDecoder(encoding).decode(uint8array);
     Streaming Decode

     var string = "", decoder = new TextDecoder(encoding), buffer;
     while (buffer = next_chunk()) {
    string += decoder.decode(buffer, {stream:true});
  }
     string += decoder.decode(); // finish the stream
   */
	send: function(command, bodyObj) {
		var commandstr = tioFormatCommand(command); //-128, 0002, 0012
		var commandname = SiteImCommandReverse[commandstr]; //HEARTBEAT_REQ
		var str = commandstr;
		if (bodyObj) {
			str = commandstr + JSON.stringify(bodyObj);
		}
		log('准备发送 ' + commandname + ":'" + str + "'");
		var uint8array = new TextEncoder().encode(str);
        log("发送前的encode处理 uint8array"+uint8array);
		//siteim_tiows在siteim_initWs中初始化  后者在在引入的时候就已经加载
        //unit8array.buffer转arraybuffer
		siteim_tiows.ws.send(uint8array.buffer);

	}
};

siteim.updateGroupid = function() {
	var x = location.pathname;
	while(x.indexOf("//") != -1) {
		x = x.replace("//", "/");
	}
	if (x.substr(x.length - 1, 1) == "/") {
		x = x + "index.html";
	}
	siteim.groupid = x;
	return x;
}

// siteim.groupid = 
siteim.updateGroupid();


$(function() {//对应原生js的window.onload事件
	siteim_initWs();

	// tt.Conf.errorStyle = 'alert';
	// tt.Conf.clearOtherError = true;
	// tt.vf.req.addId('siteim_chat_text');
});
